package com.woniu.order.util;

import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.woniu.order.dto.PayInfoDto;
import com.woniu.order.form.AlipayForm;
import com.woniu.order.form.UserRefundForm;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.UUID;

@Component
public class AlipayUtil {
    @Resource
    private AlipayClient alipayClient;

    /**
     * 网页支付方法 参数:封装支付参数，需要包含订单号、支付金额、支付说明、详细描述（可选）、同步回调地址、异步回调地址
     */
    public String pagePay(AlipayForm form) throws Exception {
        // 实例化网页支付请求对象
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 设置参数
        String content = "{\"timeout_express\":\""+form.getPayTimeBorder()+"m\",\"out_trade_no\":\"" + form.getOrderNum() + "\"," + "\"total_amount\":\"" + form.getMoney()
                + "\"," + "\"subject\":\"" + form.getSubject() + "\"," + "\"body\":\"" + form.getBody() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}";
        request.setBizContent(content);
        //设置同步回调和异步回调
        request.setReturnUrl(form.getReturnUrl());
        request.setNotifyUrl(form.getNotifyUrl());
        //执行网页支付请求
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        //判断支付宝响应结果
        if(response.isSuccess()) {
            //返回支付宝响应的支付表单html内容
            return response.getBody();
        }
        throw new Exception("发起支付失败");
    }
    //查询支付状态
    public PayInfoDto queryPayStatus(String orderNum)throws Exception{
        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        //请二选一设置
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ orderNum+"\"}");
        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        //输出
        String orderInfo= JSONUtil.parseObj(result).get("alipay_trade_query_response").toString();
        String payCode=JSONUtil.parseObj(orderInfo).get("code").toString();
        //当支付宝响应的code为10000时说明用户已完成支付
        if("10000".equals(payCode)) {
            String payDate =JSONUtil.parseObj(orderInfo).get("send_pay_date").toString();
            String payState = JSONUtil.parseObj(orderInfo).get("trade_status").toString();
            PayInfoDto dto = new PayInfoDto(payDate, payState);
            return dto;
        }else {
            PayInfoDto dto = new PayInfoDto(null, "TRADE_FAIL");
            return dto;
        }
    }
    //退款
    public String refund(UserRefundForm form)throws Exception{
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        String out_trade_no=form.getOrderNum();
        BigDecimal money = form.getOrderMoney();
        String reason = form.getRemark();
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"refund_amount\":\""+ money +"\","
                + "\"refund_reason\":\""+ reason +"\","
                + "\"out_request_no\":\""+ UUID.randomUUID().toString() +"\"}");

//请求
        String result = alipayClient.execute(alipayRequest).getBody();
        return result;
    }
}
